
package com.xyrl.project.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author pm-zhongp
 * @ClassName: CheckMobilePad
 * @Description: 检查request 浏览器头信息中 userAgent 判断访问是来自手机 或者pad
 * @date 2015-8-14 下午04:30:54
 */
public class CheckDeviceUtil {

    // \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),
    // 字符串在编译时会被转码一次,所以是 "\\b"
    // \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)

    static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
            + "|windows (phone|ce)|blackberry"
            + "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
            + "|laystation portable)|nokia|fennec|htc[-_]"
            + "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
    static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
            + "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";

    //移动设备正则匹配：手机端、平板
    static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
    static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);
    public static final String DEVICE_IOS = "ios";
    public static final String DEVICE_ANDROID = "android";

    /**
     * @param userAgent
     * @return 传入参数
     * @throws
     * @Title: checkIsMobile
     * @Description: 判断是否手机访问
     * @author pm-zhongp
     * @createTime 2015-8-14 下午04:31:50
     */
    public static boolean checkIsMobile(String userAgent) {
        if (null == userAgent) {
            userAgent = "";
        }
        // 匹配
        Matcher matcherPhone = phonePat.matcher(userAgent);
        if (matcherPhone.find()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param userAgent
     * @return 传入参数
     * @throws
     * @Title: checkIsPad
     * @Description: 判断是否pad访问
     * @author pm-zhongp
     * @createTime 2015-8-14 下午04:32:06
     */
    public static boolean checkIsPad(String userAgent) {
        if (null == userAgent) {
            userAgent = "";
        }
        // 匹配
        Matcher matcherTable = tablePat.matcher(userAgent);
        if (matcherTable.find()) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 获取请求设备类型
     * @author 徐恩源
     * @date 2019-12-27 17:08:43
     * @param userAgent
     */
    public static String getDevice(String userAgent) {
        if (userAgent.indexOf("android") != -1) {
            return DEVICE_ANDROID;
        } else if (userAgent.indexOf("iphone") != -1 || userAgent.indexOf("ipad") != -1 || userAgent.indexOf("ipod") != -1) {
            //苹果
            return DEVICE_IOS;
        }
        return "未知";
    }
}
